<template>
  <div class="p-2">
    <el-form :model="queryParams" v-show="showSearch" :inline="true">
      <el-form-item label="用户名" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户名"
          clearable
          style="width: 240px"
          @keyup.enter="fetchTableData"
        />
      </el-form-item>
      <el-form-item label="用户状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择用户状态"
          clearable
          style="width: 240px"
          @keyup.enter="fetchTableData"
        >
          <el-option label="正常" value="0" />
          <el-option label="停用" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="fetchTableData"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <div class="flex justify-between">
      <el-button
        type="primary"
        plain
        icon="Plus"
        @click="handleAdd"
        v-permission="['system.user.add']"
        >新增</el-button
      >
      <div>
        <el-tooltip
          effect="dark"
          :content="showSearch ? '隐藏搜索' : '展示搜索'"
          placement="top"
        >
          <el-button
            circle
            icon="Search"
            @click="showSearch = !showSearch"
            loop="展示搜索"
          />
        </el-tooltip>
        <el-tooltip effect="dark" content="刷新" placement="top">
          <el-button circle icon="RefreshLeft" @click="fetchTableData" />
        </el-tooltip>
      </div>
    </div>
    <el-table
      v-loading="loading"
      :data="userList"
      style="width: 100%"
      class="mt-2"
    >
      <el-table-column prop="userName" label="用户名" width="180" />
      <el-table-column label="用户类型" width="180">
        <template #default="scope">
          {{ scope.row.userType === "00" ? "系统用户" : "其他" }}
        </template>
      </el-table-column>
      <el-table-column label="用户状态" width="180">
        <template #default="scope">
          <el-switch
            v-permission="['system.user.freeze']"
            v-if="scope.row.userId !== 1"
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column label="操作">
        <template #default="scope">
          <el-tooltip content="编辑" placement="top">
            <span v-permission="['system.user.edit']">
              <el-button
                v-if="scope.row.userId !== 1"
                type="primary"
                icon="Edit"
                link
                @click="handleEdit(scope.row)"
              />
            </span>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <span v-permission="['system.user.remove']">
              <el-button
                v-if="scope.row.userId !== 1"
                type="primary"
                icon="Delete"
                link
                @click="handleDelete(scope.row)"
              />
            </span>
          </el-tooltip>
          <el-tooltip content="修改密码" placement="top">
            <span v-permission="['system.user.updatePassword']">
              <el-button
                v-if="scope.row.userId !== 1"
                type="primary"
                icon="Lock"
                link
                @click="handleUpdatePassword(scope.row)"
              />
            </span>
          </el-tooltip>
          <el-tooltip content="分配角色" placement="top">
            <span v-permission="['system.user.assign']">
              <el-button
                v-if="scope.row.userId !== 1"
                type="primary"
                icon="Avatar"
                link
                @click="handleAssignRole(scope.row)"
              />
            </span>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      class="justify-end mt-4 d-flex"
      v-model:current-page="queryParams.pageNum"
      v-model:page-size="queryParams.pageSize"
      :page-sizes="[10, 20, 30, 50]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="fetchTableData"
      @current-change="fetchTableData"
    />
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="30%"
      :before-close="handleClose"
    >
      <el-form
        ref="formRef"
        :model="userForm"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="userForm.userName" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!userForm.userId">
          <el-input v-model="userForm.password" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="submitForm(formRef)">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改密码弹窗 -->
    <el-dialog
      v-model="passwordDialogVisible"
      title="修改密码"
      width="30%"
      :before-close="handlePasswordClose"
    >
      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        label-width="120px"
      >
        <el-form-item label="密码" prop="password">
          <el-input v-model="passwordForm.password" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handlePasswordClose">取消</el-button>
          <el-button
            type="primary"
            @click="submitPasswordForm(passwordFormRef)"
          >
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 分配角色弹窗 -->
    <el-dialog
      v-model="assignRoleDialogVisible"
      title="分配角色"
      width="30%"
      :before-close="handleAssignRoleClose"
    >
      <el-form :model="assignRoleForm" label-width="120px">
        <el-form-item label="角色">
          <el-select
            v-model="assignRoleForm.roleIds"
            multiple
            placeholder="请选择角色"
            style="width: 240px"
          >
            <el-option
              v-for="item in assignRoleForm.allRoles"
              :key="item.roleId"
              :label="item.roleName"
              :value="item.roleId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleAssignRoleClose">取消</el-button>
          <el-button type="primary" @click="submitAssignRoleForm()">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import {
  getUserList,
  addUser,
  updateUser,
  deleteUser,
  updateUserPassword,
  updateUserFreeze,
  getUserAssignRole,
  assignRole,
} from "@/api/system/user";
const assignRoleDialogVisible = ref(false);
const formRef = ref(null);
const passwordFormRef = ref(null);
const passwordDialogVisible = ref(false);
const loading = ref(false);
const showSearch = ref(true);
const total = ref(0);
const userList = ref([]);
const dialogVisible = ref(false);
const dialogTitle = ref("");
const assignRoleForm = ref({
  userId: null,
  roleIds: [],
  allRoles: [],
});
const rules = ref({
  userName: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 3, max: 20, message: "用户名长度必须在3-20位之间", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 5, max: 20, message: "密码长度必须在5-20位之间", trigger: "blur" },
  ],
});
const passwordRules = ref({
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 5, max: 20, message: "密码长度必须在5-20位之间", trigger: "blur" },
  ],
});
const passwordForm = ref({
  userId: null,
  password: "",
});
// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  userName: "",
  status: "",
});
// 用户表单数据
const userForm = ref({
  userId: null,
  userName: "",
  password: "",
});
// 关闭用户弹窗
function handleClose() {
  resetUserForm();
  dialogVisible.value = false;
}
// 提交角色表单
function submitForm(formRef) {
  formRef.validate().then(async () => {
    if (userForm.value.userId) {
      await updateUser({
        userId: userForm.value.userId,
        userName: userForm.value.userName,
      });
    } else {
      await addUser(userForm.value);
    }
    dialogVisible.value = false;
    resetUserForm();
    fetchTableData();
  });
}
// 重置用户表单
function resetUserForm() {
  userForm.value = {
    userId: null,
    userName: "",
    password: "",
  };
}
function handleAdd() {
  dialogTitle.value = "新增用户";
  dialogVisible.value = true;
}
function handleEdit(row) {
  userForm.value = { ...row };
  dialogTitle.value = "编辑用户";
  dialogVisible.value = true;
}
function handleDelete(row) {
  ElMessageBox.confirm("确定删除吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await deleteUser(row.userId);
    fetchTableData();
  });
}
// 分配角色
async function handleAssignRole(row) {
  const res = await getUserAssignRole(row.userId);
  assignRoleForm.value.allRoles = res.allRoles;
  assignRoleForm.value.roleIds = res.roleIds;
  assignRoleForm.value.userId = row.userId;
  assignRoleDialogVisible.value = true;
}
// 提交分配角色表单
async function submitAssignRoleForm() {
  await assignRole(assignRoleForm.value);
  handleAssignRoleClose();
}
// 关闭分配角色弹窗
function handleAssignRoleClose() {
  assignRoleForm.value = {
    userId: null,
    roleIds: [],
    allRoles: [],
  };
  assignRoleDialogVisible.value = false;
}
// 提交修改密码表单
function submitPasswordForm(formRef) {
  formRef.validate().then(async () => {
    await updateUserPassword(passwordForm.value);
    handlePasswordClose();
  });
}
// 修改密码
function handleUpdatePassword(row) {
  passwordForm.value.userId = row.userId;
  passwordDialogVisible.value = true;
}
// 关闭修改密码弹窗
function handlePasswordClose() {
  passwordDialogVisible.value = false;
  passwordForm.value = {
    userId: null,
    password: "",
  };
}
// 变更用户状态
function handleStatusChange(row) {
  ElMessageBox.confirm("确定变更用户状态吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      await updateUserFreeze({
        userId: row.userId,
        status: row.status,
      });
    })
    .catch(() => {
      ElMessage({
        message: "已经取消",
        type: "info",
      });
      row.status = row.status === "0" ? "1" : "0";
    });
}
// 重置查询
async function resetQuery() {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    userName: "",
    status: "",
  };
  fetchTableData();
}
// 查询用户
async function fetchTableData() {
  loading.value = true;
  const res = await getUserList(queryParams.value);
  userList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

onMounted(() => {
  fetchTableData();
});
</script>
<style scoped></style>
